package com.example.armmvvm.ui.fallview

import android.view.View
import android.view.ViewGroup
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.lifecycleScope
import com.example.armmvvm.ui.view.IBottomSheetBehavior
import kotlinx.coroutines.launch

/**
 * @author 创建人 ：yanghaozhang
 * @version 1.0
 * @package 包名 ：com.augurit.agmobile.agwater5.drainage.pipereview.base
 * @createTime 创建时间 ：2021/3/26
 * @modifyBy 修改人 ：
 * @modifyTime 修改时间 ：
 * @modifyMemo 修改备注：
 */
abstract class AnchorFallView(
    lifecycleOwner: LifecycleOwner,
    val viewContainer: ViewGroup,
    val layoutResId: Int,
    val state: Int = IBottomSheetBehavior.STATE_COLLAPSED
) : BaseFallView(lifecycleOwner) {

    var fallViewSetting: AnchorFallViewSetting? = null

    // 弹窗BottomBehavior的管理者
    protected val controller = AnchorFallViewController.getInstance(viewContainer, lifecycleOwner)

    override fun show() {
        lifecycleOwner.lifecycle.addObserver(this)
        lifecycleOwner.lifecycleScope.launch {
            val attachView = controller.attachView(layoutResId)
            updateView(attachView)
            controller.showBottomView(createBottomFallViewSetting(attachView), state)
            afterShow(attachView)
        }
    }

    override fun dismiss() {
        if (isShowing()) {
            controller.hideBottomView()
        }
    }

    override fun isShowing(): Boolean {
        return controller.isShowing() && controller.currentFallView == fallViewSetting
    }

    private fun createBottomFallViewSetting(view: View): AnchorFallViewSetting {
        return (bottomFallViewSetting(view) ?: AnchorFallViewSetting(view)).apply {
            fallViewSetting = this
            hideCallBack = {
                onDismiss()
            }
        }
    }

    //-----------------子类实现方法--------------------------

    /**
     * 监听Behavior状态改变等
     */
    open fun bottomFallViewSetting(view: View): AnchorFallViewSetting? = null
}